package com.hntnbs.websocket.servers;

import com.hntnbs.rabbitmq.utils.MQUtil;
import com.hntnbs.websocket.entity.SessionContainer;
import com.hntnbs.websocket.utils.SocketUtil;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint(value = "/broadcastWebSocket")
@Component
public class BroadcastWebSocketServer extends AbstractWebSocketServer {

    private Session session;
    public static ConcurrentHashMap<String, SessionContainer> webSockets = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        SessionContainer container = new SessionContainer();
        container.setSession(session);
        container.setConnectTime(new Date());
        container.setExchangeName("directExchange2");
        container.setRoutingKey("rabbit.msg");
        webSockets.put(session.getId(), container);
        SocketUtil.send(session, "新用户加入");
    }

    @OnClose
    public void onClose(Session session) {
        webSockets.remove(this);
    }

    @OnMessage
    public void onMessage(Session session, String msg) {
        System.out.println("从客服端" + session.getId() + "接受的消息： " + msg);
        SessionContainer container = webSockets.get(session.getId());
        MQUtil.send(container.getExchangeName(), container.getRoutingKey(), msg);
    }

    @Override
    public final Session getSession() {
        return this.session;
    }
}
